package org.ihelpuoo.util.exp;

import java.io.IOException;
import java.io.Reader;

import org.ihelpuoo.io.TextTokenReader;
import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.parser.AbstractTextParser;

import bsh.EvalError;
import bsh.Interpreter;

public class BooleanExpressionImpl extends AbstractTextParser implements BooleanExpression
{
	private Interpreter			bsh			= new Interpreter();

	private static final String	_funcName	= "expression()";

	public boolean isTrue()
	{
		Object ret = null;
		try
		{
			ret = bsh.eval(_funcName);
		}
		catch (EvalError e)
		{
			throw new RuntimeException(e);
		}
		if (ret instanceof Boolean)
		{
			return ((Boolean)ret).booleanValue();
		}
		return false;
	}

	/**
	 * set Object param for expression
	 * 
	 * @param paramName
	 * @param value
	 */
	public void setParam(String paramName, Object value)
	{
		try
		{
			bsh.set(paramName,value);
		}
		catch (EvalError e)
		{
			throw new RuntimeException(e);
		}
	}

	public void parse(Reader r) throws LoaderException
	{
		try
		{
			// clear old params.
			TextTokenReader ttr = new TextTokenReader(r);
			this.clearParams();
			bsh.eval(_funcName + "{ return " + ttr.readAll() + ";}");
		}
		catch (IOException e)
		{
			throw new LoaderException(e);
		}
		catch (EvalError e)
		{
			throw new LoaderException(e);
		}
	}

	/**
	 * Clear the old params used in last expression. <br>
	 * And build a clean envariment for new expression
	 * 
	 * @throws EvalError
	 */
	private void clearParams() throws EvalError
	{
		// clear the old params for save memory
		bsh.getNameSpace().clear();
	}
}
